<?php
/**
 * Hello World default controller
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 * @license		GNU/GPL
 */

jimport('joomla.application.component.controller');

/**
 * Hello World Component Controller
 *
 * @package		HelloWorld
 */
class ShopController extends JController
{
    static $prop;

    static function conf ($reload=false) {
        if (!$reload && !empty(self::$prop)) return self::$prop;
        $db = &JFactory::getDBO();
        $db->setQuery('SELECT * FROM #__shop_config');
        self::$prop = $db->loadObject();
        // Пушистики конфига
        self::$prop->all_models_cats = json_decode(self::$prop->all_models_cats);
        self::$prop->min_price = str_replace('{min_price_rub}', self::$prop->min_price_rub, self::$prop->min_price);
        return self::$prop;
    }
    /**
     * Method to display the view
     *
     * @access	public
     */
    function display()
    {
            parent::display();
    }

    function changeMainImage(){
            $id = JRequest::getInt('id',0);
            $img = JRequest::getVar('img');

            $db = &JFactory::getDBO();
            $db->setQuery('SELECT main_img,add_img FROM #__shop_prod WHERE id='.$id);
            $good = $db->loadObject();
            $add = explode(';',$good->add_img);
            if(($k = array_search($img,$add)) !==false){
                    //unlink($add[$k]);
                    $add[$k]=$good->main_img;
                    $add = implode(';',$add);
                    $db->setQuery("UPDATE #__shop_prod SET main_img='".$img."',add_img='".$add."' WHERE id=".$id);
                    $db->query();
            }
            $this->setRedirect(JRoute::_('index.php?option=com_shop&view=new_good&cid='.$id, false));
    }

    function editCat()
    {
    $cid = JRequest::getVar('cid');

        $link = JRoute::_('index.php?option=com_shop&view=new_category&cid='. $cid[0], false);
        $this->setRedirect($link);
    }
    function addCat()
    {
        $cid = 0;
        $link = JRoute::_('index.php?option=com_shop&view=new_category&cid='. $cid[0], false);
        $this->setRedirect($link);
    }
    function cancelCat()
    {
	    $link = JRoute::_('index.php?option=com_shop&view=categories', false);
	    $this->setRedirect($link);
    }

    function delCat()
    {
     	$cid = JRequest::getVar('cid');
        $model = $this->getModel('categories');

        if ($model->delete($cid)) {
            $message = JText::_('Категория удалена');
        } else {
            $message = JText::_('Ошибка !');
        }

    	$link = 'index.php?option=com_shop&view=categories';
	    $this->setRedirect($link, $message);
    }
	
    function saveCat()
    {
    //	JRequest::setVar('view', 'categories');
            $data = JRequest::get('post');
            var_dump($data);
            $model = $this->getModel('new_category');
    //	$data = array();
    /*	$data['id'] = JRequest::getVar('id','','post','integer');
            $data['descr'] = JRequest::getVar('descr', '', 'post', 'string', JREQUEST_ALLOWRAW );
            $data['name'] =  JRequest::getVar('name','','post','string');*/
            if ($model->store($data)) {
        $message = JText::_('Категория добавлена !');
    } else {
        $message = JText::_('Ошибка !');
    }
            $this->setRedirect(JRoute::_('index.php?option=com_shop&view=categories', false), $message);
    }
    function editPay()
    {
    	$cid = JRequest::getVar('cid');
		
	    $link = JRoute::_('index.php?option=com_shop&view=payment&cid='. $cid[0], false);
	    $this->setRedirect($link);
    }
    function addPay()
    {
    $cid = 0;

        $link = JRoute::_('index.php?option=com_shop&view=payment&id='. $cid, false);
        $this->setRedirect($link);
    }
    function cancelPay()
    {
        $link = JRoute::_('index.php?option=com_shop&view=payment', false);
        $this->setRedirect($link);
    }

    function delPay()
    {
     	$cid = JRequest::getVar('cid');
        $model = $this->getModel('payment');

        if ($model->delete($cid)) {
            $message = JText::_('Оплата удалена');
        } else {
            $message = JText::_('Ошибка !');
        }

    	$link = 'index.php?option=com_shop&view=payment';
	    $this->setRedirect($link, $message);
    }
	
    function savePay()
    {
    //	JRequest::setVar('view', 'categories');
            $data = JRequest::get('post');
            var_dump($data);
            $model = $this->getModel('payment');
    //	$data = array();
    /*	$data['id'] = JRequest::getVar('id','','post','integer');
            $data['descr'] = JRequest::getVar('descr', '', 'post', 'string', JREQUEST_ALLOWRAW );
            $data['name'] =  JRequest::getVar('name','','post','string');*/
            if ($model->store($data)) {
        $message = JText::_('Способ оплаты добавлен !');
    } else {
        $message = JText::_('Ошибка !');
    }
            $this->setRedirect(JRoute::_('index.php?option=com_shop&view=payment', false), $message);
    }
	
	
    function editGood()
    {
    $cid = JRequest::getVar('cid');
            $page = JRequest::getVar('pager');
            $cat = JRequest::getVar('cat');
        $link = JRoute::_('index.php?option=com_shop&view=new_good&cid='. $cid[0].'&pager='.$page.'&cat='.$cat, false);
        $this->setRedirect($link);
    }
    function addGood()
    {
    $cid = 0;

        $link = JRoute::_('index.php?option=com_shop&view=new_good&cid='. $cid[0], false);
        $this->setRedirect($link);
    }
    function cancelGood()
    {
        $link = JRoute::_('index.php?option=com_shop&view=goods', false);
        $this->setRedirect($link);
    }

    function delGood()
    {
     	$cid = JRequest::getVar('cid');
        $model = $this->getModel('goods');

        if ($model->delete($cid)) {
            $message = JText::_('Товар удален');
        } else {
            $message = JText::_('Ошибка !');
        }

    	$link = 'index.php?option=com_shop&view=goods';
	    $this->setRedirect($link, $message);
    }
	
    function saveGood()
    {
            JRequest::setVar('view', 'goods');

            $data = JRequest::get('post');
            $db=JFactory::getDBO();
            $db->setQuery('SELECT cat_id FROM #__shop_prod WHERE id='.(int)$data[id]);
            $cat_id = $db->loadResult();
            $model = $this->getModel('new_good');
    //	$data = array();
    /*	$data['id'] = JRequest::getVar('id','','post','integer');
            $data['descr'] = JRequest::getVar('descr', '', 'post', 'string', JREQUEST_ALLOWRAW );
            $data['name'] =  JRequest::getVar('name','','post','string');*/
            if ($model->store($data)) {
        $message = JText::_('Товар добавлен!');
    } else {
        $message = JText::_('Ошибка !');
    }
            $this->setRedirect(JRoute::_('index.php?option=com_shop&view=goods&cat_id='.$data[cat].'&page='.$data[pager], false), $message);
    }
    function applyGood(){

            $data = JRequest::get('post');
            //echo '<pre>';
            //var_dump($data);
            //exit;
            $model = $this->getModel('new_good');
    //	$data = array();
    /*	$data['id'] = JRequest::getVar('id','','post','integer');
            $data['descr'] = JRequest::getVar('descr', '', 'post', 'string', JREQUEST_ALLOWRAW );
            $data['name'] =  JRequest::getVar('name','','post','string');*/
            if ($model->store($data)) {
        $message = JText::_('Товар добавлен!');
    } else {
        $message = JText::_('Ошибка !');
    }
            $this->setRedirect(JRoute::_('index.php?option=com_shop&view=new_good&cid='.$data[id], false));
    }
    function changePub()
    {
            $id = JRequest::getInt('id');
            $db = & JFactory::getDBO();
            $query = "SELECT * FROM #__nix_payment WHERE id=".$id;
            $db->setQuery($query);
            if($db->loadResult() != null)
            {
                    $pay = $db->loadObject();
                    if($pay->published == 1)
                            $query = "UPDATE #__nix_payment SET published=0 WHERE id=$id";
                    else
                            $query = "UPDATE #__nix_payment SET published=1 WHERE id=$id";

                    $db->setQuery($query);
                    $db->query();
                    $this->setRedirect(JRoute::_('index.php?option=com_shop&view=settings', false), 'Статус способа оплаты сменен');
            }
            else
                    $this->setRedirect(JRoute::_('index.php?option=com_shop&view=settings', false), 'Ошибка');
    }
    
    function saveUpdateCost () {
        $oConf = self::conf();
        $data = JRequest::get('post');
        //printu($data,'data');
        $db = & JFactory::getDBO();
        if ($data['update_cost'] !='' ) {
            $_SESSION['update_cost']['res'] = array();
            $sNonCat = '';
            if ($oConf->non_update_cost != '') {
                $sNonCat = 'cat_id NOT IN ('.$oConf->non_update_cost.') ';
            }
            
            // single line
            if ((int)$data['update_cost'] != 0) {
                $sql = "SELECT *FROM #__shop_cost WHERE id = '".(int)$data['update_cost']."'";
                $db->setQuery($sql);
		$oLine = $db->loadObject();
                //printu($oLine,'Line');
                if (!$oLine) {
                    $_SESSION['update_cost']['res'][(int)$data['update_cost']][] = 'Диапазон не найден';
                    $this->setRedirect('index.php?option=com_shop&view=cost');
                    return;
                }
                $_SESSION['update_cost']['res'][(int)$data['update_cost']][] = 'Диапазон ('.$oLine->price_min.'-'.$oLine->price_max.')';
                $sql = "UPDATE #__shop_prod SET
                    price = ROUND((whole_price * {$oLine->koef}),-1)
                    WHERE ".$sNonCat." AND whole_price >= '{$oLine->price_min}' AND whole_price <= '{$oLine->price_max}'";
                $db->setQuery($sql);
                $db->query();
                $upd_goods = $db->getAffectedRows();
                $_SESSION['update_cost']['res'][(int)$data['update_cost']][] = 'Обновлено товаров: '.$upd_goods;
                $this->setRedirect('index.php?option=com_shop&view=cost');
                return;
            }

            // all lines
            $sql = "SELECT * FROM #__shop_cost";
            $db->setQuery($sql);
            $items = $db->loadObjectList();
            foreach ($items as $oLine) {
                $_SESSION['update_cost']['res']['all'][] = 'Диапазон ('.$oLine->price_min.'-'.$oLine->price_max.')';
                $sql = "UPDATE #__shop_prod SET
                    price = ROUND((whole_price * {$oLine->koef}),-1)
                    WHERE ".$sNonCat." AND whole_price >= '{$oLine->price_min}' AND whole_price <= '{$oLine->price_max}'";
                $db->setQuery($sql);
                $db->query();
                $upd_goods = $db->getAffectedRows();
                $_SESSION['update_cost']['res']['all'][] = 'Обновлено товаров: '.$upd_goods;
            }
            $this->setRedirect('index.php?option=com_shop&view=cost');
            return;
        }
        
        foreach ($data['price_min'] as $id=>$val) {

            $sql = "UPDATE #__shop_cost SET
                price_min = '{$val}',
                price_max = '{$data['price_max'][$id]}',
                koef = '{$data['koef'][$id]}',
                for_new = '".(isset($data['for_new'][$id])?'1':'0')."',
                for_upd = '".(isset($data['for_upd'][$id])?'1':'0')."'
            WHERE id = '{$id}'";
            $db->setQuery($sql);
            //printu($sql,'$sql');
            $db->query();
        }
        if (isset($data['cid'])) {
            $del_items = implode("','",$data['cid']);
            $sql = "DELETE FROM #__shop_cost WHERE id IN ('".$del_items."') ";
            $db->setQuery($sql);
            $db->query();
        }
        if ((int)$data['new_max'] != 0 && (float)$data['new_koef'] != 0) {

            $sql = "INSERT INTO #__shop_cost
                (price_min,price_max,koef,for_new,for_upd)
                VALUES
                ('".(int)$data['new_min']."','".(int)$data['new_max']."',
                 '".(float)$data['new_koef']."',
                 '".(isset($data['new_for_new'])?1:0)."','".(isset($data['new_for_upd'])?1:0)."')";
            //printu($sql,'sql');
            $db->setQuery($sql);
            $db->query();
            $insertid = $db->insertid();
            //printu($insertid,'$insertid');
            if($db->getErrorMsg() == ''){
                printu($db->getErrorMsg(),'$db->getErrorMsg()');
                die;
            }
            //die;
        }
        //die('save opt');
        $this->setRedirect('index.php?option=com_shop&view=cost');
    }

    function cancelUpdateCost () {
        $this->setRedirect('index.php?option=com_shop&view=cost');
    }

    function saveConfig()
    {
        //$configfile = JPATH_COMPONENT . DS . 'config.shop.php';
        //$oConf = self::conf();
        $data = JRequest::get('post');
        $check_text =  JRequest::getVar( 'check_text', '', 'post', 'string', JREQUEST_ALLOWRAW );
        $delivery =  JRequest::getVar( 'delivery', '', 'post', 'string', JREQUEST_ALLOWRAW );
        $all_models_cats = "{";
        $all_models_cats .= '"dress":"'.mysql_escape_string($data['all_models_dress']).'",';
        $all_models_cats .= '"sex":"'.mysql_escape_string($data['all_models_sex']).'"}';
        $non_update_cost = implode(',',$data['non_update_cost']);
        //printu($data['non_update_cost'],'non_update_cost'); die;
        $sql = "UPDATE jos_shop_config SET
            small_width = '".(int)$data['small_width']."',
            small_height = '".(int)$data['small_height']."',
            all_models_cats = '".$all_models_cats."',
            min_price_rub = '".(int)$data['min_price_rub']."',
            min_price = '".mysql_escape_string($data['min_price'])."',
            non_update_cost = '".trim($non_update_cost)."',
            email_adress = '".mysql_escape_string($data['email_adress'])."',
            email_adress_copy = '".mysql_escape_string($data['email_adress_copy'])."',
            email_text_receipt = '".$_POST['email_text_receipt']."',
            email_text_processing = '".$_POST['email_text_processing']."',
            email_text_warehouse = '".$_POST['email_text_warehouse']."',
            email_text_discount = '".$_POST['email_text_discount']."',
            delivery = '{$delivery}'
            WHERE id = '1'";
        $db = &JFactory::getDBO();
        $db->Execute($sql);
        $this->setRedirect('index.php?option=com_shop&view=settings');
    }
	
    function cancelConfig()
    {
        $this->setRedirect('index.php?option=com_shop&view=settings');
    }
	
	function saveUpdateConfig()
	{
		$data = JRequest::get('post');
		$db = &JFactory::getDBO();
		$query = "DELETE FROM #__shop_category_comparison";
		$db->setQuery($query);
		$db->query();
		
		foreach($data[compare] as $original_id=>$compare){
			$query = "";
			if($compare != 0){
				$query = "INSERT INTO #__shop_category_comparison (id_original,id_onsite) VALUES ('".$original_id."','".$compare."')";
				$db->setQuery($query);
				$db->query();
			}
		}
		
		$this->setRedirect('index.php?option=com_shop&view=update_settings');
	}
	
	function cancelUpdateConfig()
	{
		$this->setRedirect('index.php?option=com_shop&view=update_settings');
	}
	
	function saveOrder($redirect = true)
	{
	//	require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'config.shop.php');
		
		$data = JRequest::get('post');
		$db = & JFactory::getDBO();
		$query = "SELECT * FROM #__shop_orders WHERE id=".((int)$data[order_id]);
		$db->setQuery($query);
		$order = $db->loadObject();
		
		// обновляем информацию о скидке комментарии менеджера и смене статуса
		if($db->loadResult() != null){ // если заказ существует
			$query = "UPDATE #__shop_orders SET manager_comment='".mysql_real_escape_string($data[manager_comment])."',status='".mysql_real_escape_string($data[status])."' WHERE id=".((int)$data[order_id]);
			$db->setQuery($query);
			$db->query();
			
		}
		if($redirect)
			$this->setRedirect('index.php?option=com_shop&view=orders');
	}
	function applyOrder(){
		$data = JRequest::get('post');
		$this->saveOrder(false);
		$this->setRedirect('index.php?option=com_shop&view=orders&id='.$data[order_id]);
	}
	
	function recalcOrder()
	{
		require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'config.nix.php');
		$oConf = self::conf();
		$data = JRequest::get('post');
		
		$db = & JFactory::getDBO();
		$query = "SELECT * FROM #__nix_orders WHERE id=".$data[order_id];
		$db->setQuery($query);
		$order = $db->loadObject();
		preg_match_all('#(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', $order->content, $content, PREG_PATTERN_ORDER);// разбиваем содержимое корзины на пары id товара - количество товара .
		$new_basket = $order->content;
		$new_sum = 0;
		if($data[discount] == '')
			$data[discount] = 0;
		foreach($data[articul] as $k=>$change)
		{
			//$change = trim($change);
			if(trim($change) != trim($content[1][$k]) && $change != '')
			{
				$query = "SELECT name,price,sec_id FROM #__nix_goods WHERE articul='".trim($change)."'";
				$db->setQuery($query);
				if($db->loadResult() != null)
				{
					$new_tovar = $db->loadObject();
					$query = "SELECT margin FROM #__nix_sections WHERE id=$new_tovar->sec_id";
					$db->setQuery($query);
					$margin = $db->loadObject();
					if($data[quantity][$k] > 0 && $data[quantity][$k]!='')
						$new_basket = preg_replace('#'.$content[1][$k].'\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', trim($change).'{<delimetr>}'.$new_tovar->name.'{<delimetr>}'.$data[quantity][$k].'{<delimetr>}'.((int)($new_tovar->price*(1+$margin->margin/100))).'{<delimetr_all>}', $new_basket,1);
					else
						$new_basket = preg_replace('#'.$content[1][$k].'\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', '', $new_basket);
				}
				
			}
			else
			{
				if($change == '')
					$new_basket = preg_replace('#'.$content[1][$k].'\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', '', $new_basket);
				else
					if($data[quantity][$k] > 0 && $data[quantity][$k]!='')
						$new_basket = preg_replace('#'.$content[1][$k].'\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', $content[1][$k].'{<delimetr>}$1{<delimetr>}'.$data[quantity][$k].'{<delimetr>}$3{<delimetr_all>}', $new_basket,1);
					else
						$new_basket = preg_replace('#'.$content[1][$k].'\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', '', $new_basket);
			}
		}
		
		foreach($data[new_articul] as $k=>$new)
		{
			$query = "SELECT name,price,sec_id FROM #__nix_goods WHERE articul='".trim($new)."'";
			$db->setQuery($query);
				if($db->loadResult() != null)
				{
					$new_tovar = $db->loadObject();
					$query = "SELECT margin FROM #__nix_sections WHERE id=$new_tovar->sec_id";
					$db->setQuery($query);
					$margin = $db->loadObject();
					if($data[new_quantity][$k] > 0 && $data[new_quantity][$k]!='')
						$new_basket .=trim($new).'{<delimetr>}'.$new_tovar->name.'{<delimetr>}'.$data[new_quantity][$k].'{<delimetr>}'.((int)($new_tovar->price*(1+$margin->margin/100))).'{<delimetr_all>}';
					
				}
				
		} 
		
		
		preg_match_all('#(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', $new_basket, $content, PREG_PATTERN_ORDER);// разбиваем содержимое корзины на пары id товара - количество товара .
		foreach($content[3] as $k=>$quan)
		{
			$query = "SELECT sec_id FROM #__nix_goods WHERE articul='".trim($change)."'";
			$db->setQuery($query);
			$tovar = $db->loadObject();
			$query = "SELECT margin FROM #__nix_sections WHERE id=$tovar->sec_id";
			$db->setQuery($query);
			$margin = $db->loadObject();
			
			$new_sum+= $quan*($content[4][$k]);
		}
		if($order->status == $data[status] || $data[status] == 'Заказ выполнен')
		{
			$query = "UPDATE #__nix_orders SET discount=".$data[discount].",manager_comment='".mysql_real_escape_string($data[manager_comment])."',status='$data[status]',content='$new_basket',sum='$new_sum' WHERE id=$data[order_id]";
			$rs = true;
		}			
		else
		{
			$query = "UPDATE #__nix_orders SET discount=".$data[discount].",manager_comment='".mysql_real_escape_string($data[manager_comment])."',status='$data[status]',content='$new_basket',sum='$new_sum' WHERE id=$data[order_id]";
			$mailer =& JFactory::getMailer();
                        $mailer->IsHTML(true);
			$mailer->setSender(array($oConf->email_adress, ''));
			$mailer->setSubject('Интернет-магазин Аланар,Информация по заказу №'.$data[order_id]);
			switch($data[status]){
				case 'Заказ принят':
					$text = $oConf->email_text_receipt;
					break;
				case 'Заказ обработан':
					$text = $oConf->email_text_processing;
					break;
				case 'Товар на складе':
					$text = $oConf->email_text_warehouse;
					break;
			}
                        $text = str_ireplace('{id}',$order->id,$text);
                        $text = str_ireplace('{date}',date("d.m.Y", strtotime($order->date)),$text);
                        //$text = str_ireplace('{content}',$order->id,$text);
                        $text = str_ireplace('{delivery_sum}',(int)$order->delivery_sum,$text);
                        $text = str_ireplace('{delivery_text}',$order->payment,$text);
                        $text = str_ireplace('{sum}',(int)$order->sum,$text);
                        $text = str_ireplace('{total_sum}',(int)$order->total_sum,$text);
                        $d_text = '';
                        if($order->discount_sum > 0){
                            $d_text = "<br>\n".$oConf->email_text_discount;
                            $d_text = str_ireplace('{discount}',$order->discount,$text);
                            $d_text = str_ireplace('{dis_sum}',$order->discount_sum,$text);
                        }
                        $text = str_ireplace('{discount}',$d_text,$text);
                        $mailer->setBody($text);

			$text = str_ireplace('$id',$order->id,$text);
			$text = str_ireplace('$date',date("d.m.Y", strtotime($order->date)),$text);
		//	preg_match_all('#(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr>\}(.*)\{<delimetr_all>\}#Uis', $new_basket, $content, PREG_PATTERN_ORDER);// разбиваем содержимое корзины на пары id товара - количество товара .
			$k=1;
			$list = '';
			foreach($content[1] as $key=>$goods)
			{
				$list .= "$k. ".$content[2][$key]." - ".$content[3][$key]." шт. - ".$content[4][$key]." руб.\n";
				$k++;
			}
			$text = str_ireplace('$content',$list,$text);
			$mailer->setBody($text);
			
			$user = JFactory::getUser($order->ownerid);
			$mailer->addRecipient($user->email);
			$mailer->addBCC("info@alanar.ru");
			$rs	= $mailer->Send();
		
		}
		if ( JError::isError($rs) ) {
			$msg	= $rs->getError();
		} else {
			$msg = $rs ? 'Информация обновлена': JText::_('The mail could not be sent');
		}
		$db->setQuery($query);
		$db->query();
		$this->setRedirect('index.php?option=com_shop&view=orders&id='.$data[order_id],$msg);
	}
	
	
	function cancelOrder()
	{
		$this->setRedirect('index.php?option=com_shop&view=orders');
	}
	
	function delOrders()
	{
		$cid = JRequest::getVar('cid');
        $model = $this->getModel('orders');

        if ($model->delete($cid)) {
            $message = JText::_('Заказ(ы) удален(ы)');
        } else {
            $message = JText::_('Ошибка !');
        }

    	$link = 'index.php?option=com_shop&view=orders';
	    $this->setRedirect($link, $message);	
	}
	function editOrder()
	{
		$cid = JRequest::getVar('cid');
		
	    $link = JRoute::_('index.php?option=com_shop&view=orders&id='. $cid[0], false);
	    $this->setRedirect($link);
	}
	
	function orderDown(){
		$this->move(1);    
	}    
	
	function orderUp(){
		$this->move(-1);    
	}    
	
	function move($direction){
		$view = JRequest::getVar('view');
    	if( $view == 'categories') {
			$cid = JRequest::getVar('cid');
	        $model = $this->getModel('categories');
	        if ($model->move($cid[0], $direction)) {
				$message = JText::_('Порядок успешно изменен');	        
			} 
			else  {
				$message = $model->getError();
			} 
			$this->setRedirect(JRoute::_('index.php?option=com_shop&view=categories', false), $message);
		} 
		if( $view == 'payment') {
			$cid = JRequest::getVar('cid');
	        $model = $this->getModel('payment');
	        if ($model->move($cid[0], $direction)) {
				$message = JText::_('Порядок успешно изменен');	        
			} 
			else  {
				$message = $model->getError();
			} 
			$this->setRedirect(JRoute::_('index.php?option=com_shop&view=payment', false), $message);
		}
		if( $view == 'on_main') {
			$cid = JRequest::getVar('cid');
	        $model = $this->getModel('on_main');
	        if ($model->move($cid[0], $direction)) {
				$message = JText::_('Порядок успешно изменен');	        
			} 
			else  {
				$message = $model->getError();
			} 
			$this->setRedirect(JRoute::_('index.php?option=com_shop&view=on_main', false), $message);
		} 
	}
	
	function deletAdditional(){// функция удаления дополнительного фото
		$id = JRequest::getInt('id'); // id товара 
		$num = JRequest::getInt('num');// номер изображения
		
		$db = &JFactory::getDBO();
		$query = "SELECT id,add_img FROM #__shop_prod WHERE id=".$id;
		$db->setQuery($query);
		$good = $db->loadObject();
		$message = 'ошибка удаления фото';
		$images = explode(';',$good->add_img);
		if($images[$num] != ''){
			@ unlink(JPATH_SITE . '/components/com_shop/images/originals'. DS . $images[$num]);
			@ unlink(JPATH_SITE . '/components/com_shop/images/small'. DS . $images[$num]);
			unset($images[$num]);
			$message = 'Фото удалено';
			$images = implode(';',$images);
			$query = 'UPDATE #__shop_prod SET add_img="'.$images.'" WHERE id='.$id;
			$db->setQuery($query);
			$db->query();
		}
		$this->setRedirect(JRoute::_('index.php?option=com_shop&view=new_good&id='.$id, false), $message);
	}
	
	function delOn_main(){
		$id = JRequest::getVar('cid');    	
		$db = &JFactory::getDBO();
		if (!$id || !is_array($id)) { 
             $message = JText::_('Ошибка !');
        }
		else{
			$query = 'SELECT prod_id FROM #__shop_onmain WHERE id IN ('.implode(',', $id).')';// проверка на правильность id
			$db->setQuery($query);
			
			if ($db->loadResult() != null) //
			{			
				$onmain = $db->loadObjectList();
				$query = 'DELETE FROM #__shop_onmain WHERE id IN ('.implode(',', $id).')'; // удаляем из таблицы 
				$db->setQuery($query);
				$db->query();
				
				
				foreach($onmain as $good) // удаляем соответствующие им картинки
				{
					$query = 'SELECT * FROM #__shop_prod WHERE id='.$good->prod_id; // получаем товары удаляемой категории
					$db->setQuery($query);
					$prod = $db->loadObject();
					$query ="UPDATE #__shop_prod SET on_main=0 WHERE id=".$good->prod_id;
					$db->setQuery($query);
					$db->query();
					if($prod->main_img != '')
						@ unlink(JPATH_SITE . '/components/com_shop/images/main_page' . DS . $prod->main_img);
				}
				
				
				$message = JText::_('Удалено с главной');
			}
		}	
		$link = 'index.php?option=com_shop&view=on_main';
	    $this->setRedirect($link, $message);
	}
	
	function editKey(){
		$id = JRequest::getVar('cid',0);
		if($id[0]>0)
			$this->setRedirect('index.php?option=com_shop&view=keywords&id='.$id[0]);
		else
			$this->setRedirect('index.php?option=com_shop&view=keywords','Нечего редактировать','error');
	}
	function addKey(){
		$cid = 0;
		
	    $link = JRoute::_('index.php?option=com_shop&view=keywords&id=0', false);
	    $this->setRedirect($link);
	}
	function cancelKey(){
		$this->setRedirect('index.php?option=com_shop&view=keywords');
	}
	function storeKey(){
		$data = JRequest::get('post');
		$db = &JFactory::getDBO();
		
		$alias = str_ireplace(' ','-',$this->_translate(mysql_real_escape_string(preg_replace('#[\\.,;:-]*#Uis', '', rtrim(mysql_real_escape_string($data[name]))))));	
			
		// получаем все описания с тегами
		$data[descr1] = JRequest::getVar( 'descr1', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data[descr2] = JRequest::getVar( 'descr2', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$data[descr3] = JRequest::getVar( 'descr3', '', 'post', 'string', JREQUEST_ALLOWRAW );
		if($data[id] == 0){
		
			
			$query = "SELECT alias FROM #__shop_keywords WHERE alias='".$alias."'";
			$db->setQuery($query);
			$alias_exist = $db->loadResult() !== null;
			$i = 1;
			while($alias_exist){
				$alias = str_ireplace(' ','-',$this->_translate(mysql_real_escape_string(preg_replace('#[\\.,;:-]*#Uis', '', rtrim(mysql_real_escape_string($data[name]))))))."_".$i;	
				
				$query = "SELECT alias FROM #__shop_keywords WHERE alias='".$alias."'";
				$db->setQuery($query);
				$alias_exist = $db->loadResult() !== null;
				$i++;					
			}
		
			$db->setQuery("INSERT INTO #__shop_keywords (name,published,descr1,descr2,descr3,metadescr,metakey,metatitle,alias) VALUES ('".mysql_real_escape_string($data[name])."',".(int)$data[published].",'".mysql_real_escape_string($data[descr1])."','".mysql_real_escape_string($data[descr2])."','".mysql_real_escape_string($data[descr3])."','".mysql_real_escape_string($data[metadescr])."','".mysql_real_escape_string($data[metakey])."','".mysql_real_escape_string($data[metatitle])."','".$alias."')");
			$message = 'Ключевое слово добавлено';
		}
		else{
					
			$query = "SELECT alias FROM #__shop_keywords WHERE alias='".$alias."' AND id!=".$data[id];			
			$db->setQuery($query);
			$alias_exist = $db->loadResult() !== null;
			$i = 1;
			while($alias_exist){
				$alias = str_ireplace(' ','-',$this->_translate(mysql_real_escape_string(preg_replace('#[\\.,;:-]*#Uis', '', rtrim(mysql_real_escape_string($data[name]))))))."_".$i;
				$query = "SELECT alias FROM #__shop_keywords WHERE alias='".$alias."' AND id!=".$data[id];				
				$db->setQuery($query);
				$alias_exist = $db->loadResult() !== null;
				$i++;					
			}		
		
			$db->setQuery("UPDATE #__shop_keywords SET name='".mysql_real_escape_string($data[name])."',descr1='".mysql_real_escape_string($data[descr1])."',descr2='".mysql_real_escape_string($data[descr2])."',descr3='".mysql_real_escape_string($data[descr3])."',metadescr='".mysql_real_escape_string($data[metadescr])."',metakey='".mysql_real_escape_string($data[metakey])."',metatitle='".mysql_real_escape_string($data[metatitle])."',published='".(int)$data[published]."',alias='".$alias."' WHERE id=".(int)$data[id]);
			$message = 'Редактирование завершено';
		}
		$db->query();
		
		$this->setRedirect('index.php?option=com_shop&view=keywords',$message);
	}
	
	function deleteKey(){
		$db = &JFactory::getDBO();
		$id = JRequest::getVar('cid',0);
		
		if($id > 0){
			$db->setQuery('DELETE From #__shop_keywords WHERE id IN ('.implode(',',$id).')');
			$db->query();
			/* TODO
				Добавить удаление ключевых слов из товаров
			*/
			$this->setRedirect('index.php?option=com_shop&view=keywords','Слова удалены');
		}
		else
			$this->setRedirect('index.php?option=com_shop&view=keywords','Нечего удалять','error');
	}
	function _translate($title)
	{
		$tbl= array(
			'а'=>'a', 'б'=>'b', 'в'=>'v', 'г'=>'g', 'д'=>'d', 'е'=>'e', 'ж'=>'g', 'з'=>'z',
			'и'=>'i', 'й'=>'y', 'к'=>'k', 'л'=>'l', 'м'=>'m', 'н'=>'n', 'о'=>'o', 'п'=>'p',
			'р'=>'r', 'с'=>'s', 'т'=>'t', 'у'=>'u', 'ф'=>'f', 'ы'=>'i', 'э'=>'e', 'А'=>'A',
			'Б'=>'B', 'В'=>'V', 'Г'=>'G', 'Д'=>'D', 'Е'=>'E', 'Ж'=>'G', 'З'=>'Z', 'И'=>'I',
			'Й'=>'Y', 'К'=>'K', 'Л'=>'L', 'М'=>'M', 'Н'=>'N', 'О'=>'O', 'П'=>'P', 'Р'=>'R',
			'С'=>'S', 'Т'=>'T', 'У'=>'U', 'Ф'=>'F', 'Ы'=>'I', 'Э'=>'E', 'ё'=>"yo", 'х'=>"h",
			'ц'=>"ts", 'ч'=>"ch", 'ш'=>"sh", 'щ'=>"shch", 'ъ'=>"", 'ь'=>"", 'ю'=>"yu", 'я'=>"ya",
			'Ё'=>"YO", 'Х'=>"H", 'Ц'=>"TS", 'Ч'=>"CH", 'Ш'=>"SH", 'Щ'=>"SHCH", 'Ъ'=>"", 'Ь'=>"",
			'Ю'=>"YU", 'Я'=>"YA", ' '=>"-", '('=>'', ')'=>'', ','=>'', '.'=>''
			);

		$translate = mb_strtolower(strtr($title, $tbl));
		return $translate;
	}

}
?>